{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dd9bbd4c",
   "metadata": {
    "colab_type": "text",
    "id": "view-in-github"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W0D4_Calculus/student/W0D4_Tutorial3.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08842220",
   "metadata": {},
   "source": [
    "# Neuromatch Academy: Week 0, Day 4, Tutorial 3\n",
    "# Numerical Methods\n",
    "\n",
    "__Content creators:__ John S Butler, Arvind Kumar\n",
    "\n",
    "__Content reviewers:__ \n",
    "\n",
    "__Production editors:__ \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d80998b",
   "metadata": {},
   "source": [
    "---\n",
    "# Tutorial Objectives\n",
    "\n",
    "While a great deal of neuroscience can be describe by mathematics a great deal of the mathematics used cannot be solved exactly. This might seem very odd that you can writing something in mathematics that cannot be immediately solved but that is the beauty and mystery of mathematics. To side step this issue we use Numerical Methods to estimate the solution.\n",
    "\n",
    "\n",
    "\n",
    "In this tutorial, we will look at the Euler method to estimate the solution of a few different differential equations, the population equation, the Leaky Integrate and Fire model and a simplified version of the Wilson-Cowan model which is a system of differential equations.\n",
    "\n",
    "**Steps:**\n",
    "- Code the Euler estimate of the Population Equation;\n",
    "- Investigate the impact of time step on the error of the numerical solution;\n",
    "- Code the Euler estimate of the Learky Integrate and Fire model for a constant input;\n",
    "- Visualize and listen to the response of the integrate for different inputs;\n",
    "- Apply the Euler method to estimate the soluton of a system of differential equations.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "m2WKZ8Dt8pmD",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:28.588767Z",
     "iopub.status.busy": "2021-06-02T02:46:28.588209Z",
     "iopub.status.idle": "2021-06-02T02:46:28.607715Z",
     "shell.execute_reply": "2021-06-02T02:46:28.607115Z"
    }
   },
   "outputs": [],
   "source": [
    "#@markdown Tutorial slides\n",
    "# you should link the slides for all tutorial videos here (we will store pdfs on osf)\n",
    "\n",
    "from IPython.display import HTML\n",
    "HTML('<iframe src=\"\" frameborder=\"0\" width=\"960\" height=\"569\" allowfullscreen=\"true\" mozallowfullscreen=\"true\" webkitallowfullscreen=\"true\"></iframe>')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5985801",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:28.612235Z",
     "iopub.status.busy": "2021-06-02T02:46:28.611672Z",
     "iopub.status.idle": "2021-06-02T02:46:28.973148Z",
     "shell.execute_reply": "2021-06-02T02:46:28.972137Z"
    }
   },
   "outputs": [],
   "source": [
    "# Import libraries\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d40abcd8",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:28.979932Z",
     "iopub.status.busy": "2021-06-02T02:46:28.978727Z",
     "iopub.status.idle": "2021-06-02T02:46:29.080559Z",
     "shell.execute_reply": "2021-06-02T02:46:29.081054Z"
    }
   },
   "outputs": [],
   "source": [
    "# @title Figure Settings\n",
    "import IPython.display as ipd\n",
    "from matplotlib import gridspec\n",
    "\n",
    "import ipywidgets as widgets  # interactive display\n",
    "from ipywidgets import Label\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "# use NMA plot style\n",
    "plt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle\")\n",
    "my_layout = widgets.Layout()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hwhtoyMMi7qj",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.102527Z",
     "iopub.status.busy": "2021-06-02T02:46:29.097186Z",
     "iopub.status.idle": "2021-06-02T02:46:29.117448Z",
     "shell.execute_reply": "2021-06-02T02:46:29.116916Z"
    }
   },
   "outputs": [],
   "source": [
    "# @title Plotting Functions\n",
    "\n",
    "time = np.arange(0, 1, 0.01)\n",
    "\n",
    "def plot_slope(dt):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      dt  : time-step\n",
    "    Returns:\n",
    "      A figure of an exponential, the slope of the exponential and the derivative exponential\n",
    "  \"\"\"\n",
    "\n",
    "  t = np.arange(0, 5+0.1/2, 0.1)\n",
    "\n",
    "  with plt.xkcd():\n",
    "\n",
    "    fig = plt.figure(figsize=(6, 4))\n",
    "    # Exponential\n",
    "    p = np.exp(0.3*t)\n",
    "    plt.plot(t, p, label='y')\n",
    "    # slope\n",
    "    plt.plot([1, 1+dt], [np.exp(0.3*1), np.exp(0.3*(1+dt))],':og',label=r'$\\frac{y(1+\\Delta t)-y(1)}{\\Delta t}$')\n",
    "    # derivative\n",
    "    plt.plot([1, 1+dt], [np.exp(0.3*1), np.exp(0.3*(1))+dt*0.3*np.exp(0.3*(1))],'-k',label=r'$\\frac{dy}{dt}$')\n",
    "    plt.legend()\n",
    "    plt.plot(1+dt, np.exp(0.3*(1+dt)), 'og')\n",
    "    plt.ylabel('y')\n",
    "    plt.xlabel('t')\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "\n",
    "def plot_StepEuler(dt):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      dt  : time-step\n",
    "    Returns:\n",
    "      A figure of one step of the Euler method for an exponential growth function\n",
    "  \"\"\"\n",
    "\n",
    "  t=np.arange(0, 1 + dt + 0.1 / 2, 0.1)\n",
    "\n",
    "  with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(6,4))\n",
    "    p=np.exp(0.3*t)\n",
    "    plt.plot(t,p)\n",
    "    plt.plot([1,],[np.exp(0.3*1)],'og',label='Known')\n",
    "    plt.plot([1,1+dt],[np.exp(0.3*1),np.exp(0.3*(1))+dt*0.3*np.exp(0.3*1)],':g',label=r'Euler')\n",
    "    plt.plot(1+dt,np.exp(0.3*(1))+dt*0.3*np.exp(0.3*1),'or',label=r'Estimate $p_1$')\n",
    "    plt.plot(1+dt,p[-1],'bo',label=r'Exact $p(t_1)$')\n",
    "    plt.vlines(1+dt,np.exp(0.3*(1))+dt*0.3*np.exp(0.3*1),p[-1],colors='r', linestyles='dashed',label=r'Error $e$')\n",
    "    plt.legend()\n",
    "    plt.ylabel('Population (millions)')\n",
    "    plt.xlabel('time(years)')\n",
    "    plt.show()\n",
    "\n",
    "## LIF PLOT\n",
    "def plot_IF(t, V, I, Spike_time):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      t  : time\n",
    "      V  : membrane Voltage\n",
    "      I  : Input\n",
    "      Spike_time : Spike_times\n",
    "    Returns:\n",
    "      figure with three panels\n",
    "      top panel: Input as a function of time\n",
    "      middle panel: membrane potential as a function of time\n",
    "      bottom panel: Raster plot\n",
    "  \"\"\"\n",
    "\n",
    "  with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(12,4))\n",
    "    gs = gridspec.GridSpec(3, 1,  height_ratios=[1, 4, 1])\n",
    "    # PLOT OF INPUT\n",
    "    plt.subplot(gs[0])\n",
    "    plt.ylabel(r'$I_e(nA)$')\n",
    "    plt.yticks(rotation=45)\n",
    "    plt.plot(t,I,'g')\n",
    "    #plt.ylim((2,4))\n",
    "    plt.xlim((-50,1000))\n",
    "    # PLOT OF ACTIVITY\n",
    "    plt.subplot(gs[1])\n",
    "    plt.plot(t,V,':')\n",
    "    plt.xlim((-50,1000))\n",
    "    plt.ylabel(r'$V(t)$(mV)')\n",
    "    # PLOT OF SPIKES\n",
    "    plt.subplot(gs[2])\n",
    "    plt.ylabel(r'Spike')\n",
    "    plt.yticks([])\n",
    "    plt.scatter(Spike_time,1*np.ones(len(Spike_time)), color=\"grey\", marker=\".\")\n",
    "    plt.xlim((-50,1000))\n",
    "    plt.xlabel('time(ms)')\n",
    "    plt.show()\n",
    "\n",
    "def plot_rErI(t, r_E, r_I):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      t   : time\n",
    "      r_E : excitation rate\n",
    "      r_I : inhibition rate\n",
    "\n",
    "    Returns:\n",
    "      figure of r_I and r_E as a function of time\n",
    "\n",
    "  \"\"\"\n",
    "  with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(6,4))\n",
    "    plt.plot(t,r_E,':',color='b',label=r'$r_E$')\n",
    "    plt.plot(t,r_I,':',color='r',label=r'$r_I$')\n",
    "    plt.xlabel('time(ms)')\n",
    "    plt.legend()\n",
    "    plt.ylabel('Firing Rate (Hz)')\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def plot_rErI_Simple(t, r_E, r_I):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      t   : time\n",
    "      r_E : excitation rate\n",
    "      r_I : inhibition rate\n",
    "\n",
    "    Returns:\n",
    "      figure with two panels\n",
    "      left panel: r_I and r_E as a function of time\n",
    "      right panel: r_I as a function of r_E with Nullclines\n",
    "\n",
    "  \"\"\"\n",
    "  with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(12,4))\n",
    "    gs = gridspec.GridSpec(1, 2)\n",
    "    # LEFT PANEL\n",
    "    plt.subplot(gs[0])\n",
    "    plt.plot(t,r_E,':',color='b',label=r'$r_E$')\n",
    "    plt.plot(t,r_I,':',color='r',label=r'$r_I$')\n",
    "    plt.xlabel('time(ms)')\n",
    "    plt.legend()\n",
    "    plt.ylabel('Firing Rate (Hz)')\n",
    "    # RIGHT PANEL\n",
    "    plt.subplot(gs[1])\n",
    "    plt.plot(r_E,r_I,'k:')\n",
    "    plt.plot(r_E[0],r_I[0],'go')\n",
    "\n",
    "    plt.hlines(0,np.min(r_E),np.max(r_E),linestyles=\"dashed\",color='b',label=r'$\\frac{d}{dt}r_E=0$')\n",
    "    plt.vlines(0,np.min(r_I),np.max(r_I),linestyles=\"dashed\",color='r',label=r'$\\frac{d}{dt}r_I=0$')\n",
    "\n",
    "    plt.legend(loc='upper left')\n",
    "\n",
    "    plt.xlabel(r'$r_E$')\n",
    "    plt.ylabel(r'$r_I$')\n",
    "    plt.show()\n",
    "\n",
    "def plot_rErI_Matrix(t, r_E, r_I, Null_rE, Null_rI):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      t   : time\n",
    "      r_E : excitation firing rate\n",
    "      r_I : inhibition firing rate\n",
    "      Null_rE: Nullclines excitation firing rate\n",
    "      Null_rI: Nullclines inhibition firing rate\n",
    "    Returns:\n",
    "      figure with two panels\n",
    "      left panel: r_I and r_E as a function of time\n",
    "      right panel: r_I as a function of r_E with Nullclines\n",
    "\n",
    "  \"\"\"\n",
    "\n",
    "  with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(12,4))\n",
    "    gs = gridspec.GridSpec(1, 2)\n",
    "    plt.subplot(gs[0])\n",
    "    plt.plot(t,r_E,':',color='b',label=r'$r_E$')\n",
    "    plt.plot(t,r_I,':',color='r',label=r'$r_I$')\n",
    "    plt.xlabel('time(ms)')\n",
    "    plt.ylabel('Firing Rate (Hz)')\n",
    "    plt.legend()\n",
    "    plt.subplot(gs[1])\n",
    "    plt.plot(r_E,r_I,'k:')\n",
    "    plt.plot(r_E[0],r_I[0],'go')\n",
    "\n",
    "    plt.plot(r_E,Null_rE,':',color='b',label=r'$\\frac{d}{dt}r_E=0$')\n",
    "    plt.plot(r_E,Null_rI,':',color='r',label=r'$\\frac{d}{dt}r_I=0$')\n",
    "    plt.legend(loc='best')\n",
    "    plt.xlabel(r'$r_E$')\n",
    "    plt.ylabel(r'$r_I$')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "SXJPvBQzik6K",
   "metadata": {},
   "source": [
    "--- \n",
    "# Section 1 Euler Method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "DYKXWaR7iwl9",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.124830Z",
     "iopub.status.busy": "2021-06-02T02:46:29.123880Z",
     "iopub.status.idle": "2021-06-02T02:46:29.191343Z",
     "shell.execute_reply": "2021-06-02T02:46:29.190695Z"
    }
   },
   "outputs": [],
   "source": [
    "#@title Video 1: Intro to Numerical Methods and the Euler Method\n",
    "from IPython.display import YouTubeVideo\n",
    "video = YouTubeVideo(id=\"ORbqe7TamVI\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtu.be/\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2BcqJS6Fcbgp",
   "metadata": {},
   "source": [
    "The Euler method is one of the most simple and elegant methods to approximate a differential. It was designed by [Leonhard Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) (1707-1783). \n",
    "Simply put we just replace the derivative in the differential equation by the formula for a line and re-arrange."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e83cd97",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "## Section 1.1: Slope of a line\n",
    "The slope is the rate of change between two points. The formula for the slope of a line between the points $(t_0,y(t_0))$ and $(t_1,y(t_1))$ is given by:\n",
    "$$ m=\\frac{y(t_1)-y(t_0)}{t_1-t_0}, $$\n",
    "which can be written as \n",
    "$$ m=\\frac{y_1-y_0}{t_1-t_0}, $$\n",
    "or as\n",
    "$$ m=\\frac{\\Delta y_0}{\\Delta t_0}, $$\n",
    "where $\\Delta y_0=y_1-y_0$ and $\\Delta t_0=t_1-t_0$ or in words as\n",
    "$$ m=\\frac{\\text{ Change in y} }{\\text{Change in t}}. $$\n",
    "The slope can be used an approximation of the derivative such that\n",
    "$$ \\frac{d}{dt}y(t)\\approx \\frac{y(t_0+\\Delta t)-y(t_0)}{t_0+\\Delta t-t_0}=\\frac{y(t_0+dt)-y(t_0)}{\\Delta t}$$\n",
    "where $\\Delta t$ is a time-step."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b667c36a",
   "metadata": {},
   "source": [
    "### Interactive Demo 1.1: Slope of a Line\n",
    "The plot below shows a function $y(t)$ in blue, its exact derivative $ \\frac{d}{dt}y(t)$ at $t_0=1$ in black and the approximate derivative calculated using the slope formula $=\\frac{y(1+\\Delta t)-y(1)}{\\Delta t}$ for different time-steps sizes $\\Delta t$ in green.\n",
    "\n",
    "Interact with the widget to see how time-step impacts the accuracy of the slope which is the estimate of the derivative."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea4a4f78",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.211764Z",
     "iopub.status.busy": "2021-06-02T02:46:29.211168Z",
     "iopub.status.idle": "2021-06-02T02:46:29.743749Z",
     "shell.execute_reply": "2021-06-02T02:46:29.744195Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown Make sure you execute this cell to enable the widget!\n",
    "my_layout.width = '450px'\n",
    "@widgets.interact(\n",
    "\n",
    "    dt=widgets.FloatSlider(1, min=0., max=4., step=.1,\n",
    "                                layout=my_layout)\n",
    "\n",
    ")\n",
    "\n",
    "def Pop_widget(dt):\n",
    "  plot_slope(dt)\n",
    "  plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "HZJ0CFaIsowQ",
   "metadata": {},
   "source": [
    "### Think! 1.1: How does the size of $dt$ affect the approximation?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "gTgFRiMhc1qm",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.752345Z",
     "iopub.status.busy": "2021-06-02T02:46:29.751764Z",
     "iopub.status.idle": "2021-06-02T02:46:29.754513Z",
     "shell.execute_reply": "2021-06-02T02:46:29.754976Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_a4085ae8.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f92ce83",
   "metadata": {},
   "source": [
    "---\n",
    "# Section 2: Population Differential Equation\n",
    "\n",
    "Linking with the differential equation tutorial, we will use the population to get an intuitive feel of Euler method to approximate the solution of a differential equation. We start with the population because it has an exact solution with no discontinuities unlike the Leaky Integrate and Fire model.\n",
    "\n",
    "The population differential equation is\n",
    "\\begin{align*}\n",
    "\\\\\n",
    "\\frac{d}{dt}\\,p(t) &= \\alpha p(t)\\\\\\\\\n",
    "p(0)&=p_0 \\quad \\text{Initial Condition}\n",
    "\\end{align*}\n",
    "\n",
    "where $p(t)$ is the population of the world and $\\alpha$ is a parameter representing birth rate, with\n",
    "the exact solution \n",
    "$$ p(t)=p_0e^{\\alpha}.$$\n",
    "\n",
    "To numerically approximate the population differential equation we replace the derivate with the slope of the line to get the discrete (not continuous) equation:\n",
    "\n",
    "\\begin{align*}\n",
    "\\\\\n",
    "\\frac{p_1-p_0}{t_1-t_0} &= \\alpha p_0\\\\\\\\\n",
    "p(0)&=p_0 \\quad \\text{Initial Condition}\n",
    "\\end{align*}\n",
    "\n",
    "where $p_1$ is the approximate of $p(t_1)$. Let $\\Delta t=t_1-t_0$ be the time step and re-arrange the equation gives\n",
    "\n",
    "\\begin{align*}\n",
    "\\color{red}{p_1}&=\\color{green}{p_0}+\\color{blue}{\\Delta t} (\\color{blue}{\\alpha} \\color{green}{p_0})\n",
    "\\end{align*}\n",
    "\n",
    "where $\\color{red}{p_1}$ is the unknown future, $\\color{green}{p_0}$ is the known current population, $\\color{blue}{\\Delta t}$ is the chosen time-step parameter and $\\color{blue}{\\alpha}$ is the given birth rate parameter.\n",
    "Another way to read the re-agranged discrete equation is:\n",
    "\n",
    "\\begin{align*}\n",
    "\\color{red}{\\text{\"Future Population\"}}&=\\color{green}{\\text{ \"Current Population\"}}+\\color{blue}{\\text{ time-step}} \\times (\\color{blue}{\\text{ \"Birth rate}}\\text{ times } \\color{green}{\\text{ Current Population\"}}).\n",
    "\\end{align*}\n",
    "\n",
    "So pretty much we can use the current population and add a bit of the dynamics of the differential equation to predict the future. We will make millions, but wait there is always an error."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72c07ea2",
   "metadata": {},
   "source": [
    "## Exercise 2: One step of Euler Method\n",
    "Given the population differential equation\n",
    "\\begin{align*}\n",
    "\\\\\n",
    "\\frac{d}{dt}\\,p(t) &= 0.3 p(t),\\\\\\\\\n",
    "p(t_0=1)&=e^{0.3},\\quad \\text{Initial Condition}\n",
    "\\end{align*}\n",
    "\n",
    "code the Euler method to estimate the population $p_1$ at $t_1=2$ given the time-step $\\Delta t=1$ (for brevity, $\\Delta t$ is `dt` in the code)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ac2ccec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.762971Z",
     "iopub.status.busy": "2021-06-02T02:46:29.762324Z",
     "iopub.status.idle": "2021-06-02T02:46:29.846100Z",
     "shell.execute_reply": "2021-06-02T02:46:29.845455Z"
    }
   },
   "outputs": [],
   "source": [
    "dt = 1    # time-step\n",
    "t_0 = 1   # initial time\n",
    "p_0 = np.exp(0.3*t_0)    # initial population\n",
    "\n",
    "########################################################################\n",
    "## TODO for students: calculate the estimate solution of p at t_1\n",
    "## Complete line of code and remove\n",
    "raise NotImplementedError(\"Student exercise: calculate the estimate solution of p at t_1\")\n",
    "########################################################################\n",
    "\n",
    "dp = ...\n",
    "p_1 = ...\n",
    "print(p_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0c1edd9",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.852544Z",
     "iopub.status.busy": "2021-06-02T02:46:29.851269Z",
     "iopub.status.idle": "2021-06-02T02:46:29.854539Z",
     "shell.execute_reply": "2021-06-02T02:46:29.854015Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_a7d8b707.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3556ef2",
   "metadata": {},
   "source": [
    "---\n",
    "# Section 3: Euler Error\n",
    "\n",
    "The solution of the Euler method $p_1$ is an estimate of the exact solution $p(t_1)$ at $t_1$ which means there is a bit of error $e_1$ which gives the equation\n",
    "\\begin{align*}\n",
    "p(t_1)&=p_1+e_1\\\\\\\\\n",
    "\\text{Rearranging}\\\\\\\\\n",
    "e_1&=p(t_1)-p_1.\n",
    "\\end{align*}\n",
    "\n",
    "Most of the time we do not know the exact answer $p(t_1)$ but in the population equation we have the exact solution\n",
    "\n",
    "$$ p(t)=p_0e^{\\alpha}.$$\n",
    "\n",
    "This means we can explore what the error looks like.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "vGxg-2k6k8hM",
   "metadata": {},
   "source": [
    "## Interactive Demo 3: Euler Error\n",
    "Interact with the widget to see how the time-step $dt$ impacts the estimate $p_1$ and the error $e_1$ of the Euler method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e72c600b",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:29.877804Z",
     "iopub.status.busy": "2021-06-02T02:46:29.876607Z",
     "iopub.status.idle": "2021-06-02T02:46:30.229440Z",
     "shell.execute_reply": "2021-06-02T02:46:30.227155Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown Make sure you execute this cell to enable the widget!\n",
    "my_layout.width = '450px'\n",
    "@widgets.interact(\n",
    "    dt=widgets.FloatSlider(.3, min=0., max=4., step=.1,\n",
    "                                layout=my_layout)\n",
    ")\n",
    "\n",
    "def Pop_widget(dt):\n",
    "  plot_StepEuler(dt)\n",
    "  plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tny6eJNtsHdf",
   "metadata": {},
   "source": [
    "## Think! 3: Effect of $\\Delta t$ on Euler Error\n",
    "\n",
    "1. What happens to the estimate $p_1$ as the time-step $\\Delta t$ increases?\n",
    "\n",
    "2. Is there a relationship between the size of $\\Delta t$ and $e_1$?\n",
    "\n",
    "3. How would you improve the error $e_1$?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "EoA90TrDdVWv",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:30.232668Z",
     "iopub.status.busy": "2021-06-02T02:46:30.232119Z",
     "iopub.status.idle": "2021-06-02T02:46:30.236320Z",
     "shell.execute_reply": "2021-06-02T02:46:30.235741Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_6376082e.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e78fc157",
   "metadata": {},
   "source": [
    "The error $e_1$ from one timestep is known as the __local error__. For the Euler method the local error is linear, that means that the error decreases linearly as a function of timestep $O(\\Delta t)$."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "972a55c4",
   "metadata": {},
   "source": [
    "## Section 3.1: Time-Steps\n",
    "In the above exercise we saw that by increasing the step size $dt$ the error between the estimate $p_1$ and the exact $p(t_1)$ increased with the largest error in the example above was for $\\Delta t=4$ which gave the interval $[1, 5]$,\n",
    "$$n=\\frac{5-1}{\\Delta t}=\\frac{5-1}{4}=1,$$\n",
    "hence only $1$ time-step of size $dt=4$, giving\n",
    "$$ t_0=1,\\ \\text{ and } t_1=5. $$\n",
    "\n",
    "To address decrease the error we divide the interval $[1, 5]$ into more steps using a smaller $\\Delta t$. \n",
    "In the plot below we use $\\Delta t=1$, which divides the interval into four segments\n",
    "$$n=\\frac{5-1}{1}=4,$$\n",
    "giving\n",
    "$$ t_0=1, \\ t_1=2, \\ t_2=3, \\ t_3=4 \\ \\text{ and } t_4=5. $$\n",
    "This can be written as\n",
    "$$ t_i=1+i\\times1, \\text{ for } i=0,\\cdots 4, $$\n",
    "and more generally as \n",
    "$$ t_i=t_0+i\\times dt, \\text{ for } i=0,\\cdots n. $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d84f02ed",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:30.262188Z",
     "iopub.status.busy": "2021-06-02T02:46:30.257958Z",
     "iopub.status.idle": "2021-06-02T02:46:30.538619Z",
     "shell.execute_reply": "2021-06-02T02:46:30.538081Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown *Execute this cell to visualize time steps*\n",
    "dt  =1\n",
    "t  =np.arange(1, 5+dt/2, dt) # Time from 1 to 5 years in 0.1 steps\n",
    "with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(8, 2))\n",
    "    plt.plot(t, 0*t, ':o')\n",
    "    plt.plot(t[0] ,0*t[0],':go',label='Initial Condition')\n",
    "    plt.text(t[0]-0.1, 0*t[0]-0.03, r'$t_0$')\n",
    "    plt.text(t[1]-0.1, 0*t[0]-0.03, r'$t_1$')\n",
    "    plt.text(t[2]-0.1, 0*t[0]-0.03, r'$t_2$')\n",
    "    plt.text(t[3]-0.1, 0*t[0]-0.03, r'$t_3$')\n",
    "    plt.text(t[4]-0.1, 0*t[0]-0.03,r'$t_4$')\n",
    "    plt.text(t[0]+0.5, 0*t[0]+0.02, r'$\\Delta t$')\n",
    "    plt.text(t[1]+0.5, 0*t[0]+0.02, r'$\\Delta t$')\n",
    "    plt.text(t[2]+0.5, 0*t[0]+0.02, r'$\\Delta t$')\n",
    "    plt.text(t[3]+0.5, 0*t[0]+0.02, r'$\\Delta t$')\n",
    "    plt.yticks([])#plt.ylabel('Population (millions)')\n",
    "    plt.xlabel('time(years)')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45c068a5",
   "metadata": {},
   "source": [
    "## Section 3.2: The Difference Equation\n",
    "Using the Euler method the differential equation is written as a series of difference equations of the form:\n",
    "\\begin{align*}\n",
    "\\color{red}{p_{i+1}}&=\\color{green}{p_i}+\\color{blue}{\\Delta t} (\\color{blue}{\\alpha} \\color{green}{p_i})\\\\\n",
    "&\\text{for } i=0,1,\\cdots n-1\n",
    "\\end{align*}\n",
    "where $\\color{red}{p_{i+1}}$ is the unknown estimate of the future population at $t_{i+1}$, $\\color{green}{p_i}$ is the known current population estimate at $t_i$, $\\color{blue}{\\Delta t}$ is the chosen time-step parameter and $\\color{blue}{\\alpha}$ is the given birth rate parameter."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "279ea532",
   "metadata": {},
   "source": [
    "### Coding Exercise 3.2: Step, step, step\n",
    "Given the population differential equation\n",
    "\\begin{align*}\n",
    "\\\\\n",
    "\\frac{d}{dt}\\,p(t) &= 0.3 p(t),\\\\\n",
    "p(t_0=1)&=e^{0.3},\\quad \\text{Initial Condition,}\n",
    "\\end{align*}\n",
    "\n",
    "code the difference equation\n",
    "\n",
    "\\begin{align*}\n",
    "\\color{red}{p_{i+1}}&=\\color{green}{p_i}+\\color{blue}{dt} (\\color{blue}{0.3} \\color{green}{p_i}),\\\\\n",
    "\\color{green}{p_0}&=e^{0.3},\\quad \\text{Initial Condition,}\\\\\n",
    "&\\text{for } i=0,1,\\cdots 4,\\\\\n",
    "\\end{align*}\n",
    "\n",
    "to estimate the population on the interval $[1,5]$ with a time-step $dt=1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b872e66",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:30.566396Z",
     "iopub.status.busy": "2021-06-02T02:46:30.563972Z",
     "iopub.status.idle": "2021-06-02T02:46:30.732255Z",
     "shell.execute_reply": "2021-06-02T02:46:30.731470Z"
    }
   },
   "outputs": [],
   "source": [
    "dt = 1\n",
    "t = np.arange(1, 5+dt/2, dt) # Time from 0 to 10 years in 0.1 steps\n",
    "n = len(t)\n",
    "p = np.ones(n)\n",
    "p[0] = np.exp(0.3*t[0]) # Initial Condition\n",
    "\n",
    "fig = plt.figure(figsize=(6, 4))\n",
    "plt.plot(t, np.exp(0.3*t), 'k', label='Exact Solution')\n",
    "\n",
    "for i in range(n-1):\n",
    "  ########################################################################\n",
    "  ## TODO for students: calculate the population step for each time point\n",
    "  ## Complete line of code and remove\n",
    "  raise NotImplementedError(\"Student exercise: calculate the population step for each time point\")\n",
    "  ########################################################################\n",
    "\n",
    "  dp = ...\n",
    "  p[i+1] = ...\n",
    "\n",
    "plt.plot(t, p,':o', label='Euler Estimate')\n",
    "plt.vlines(t, p, np.exp(0.3*t),\n",
    "           colors='r', linestyles='dashed', label=r'Error $e_i$')\n",
    "\n",
    "plt.ylabel('Population (millions)')\n",
    "plt.legend()\n",
    "plt.xlabel('Time (years)')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99f943fc",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:30.734849Z",
     "iopub.status.busy": "2021-06-02T02:46:30.734295Z",
     "iopub.status.idle": "2021-06-02T02:46:31.042132Z",
     "shell.execute_reply": "2021-06-02T02:46:31.042580Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_92263c87.py)\n",
    "\n",
    "*Example output:*\n",
    "\n",
    "<img alt='Solution hint' align='left' width=416 height=272 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W0D4_Calculus/static/W0D4_Tutorial3_Solution_92263c87_0.png>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9301447",
   "metadata": {},
   "source": [
    "The error is smaller for 4 time-step than taking one large time step from 1 to 5 but do note that the error is increasing for each step, this is known as __global error__ so the futher in time you want to predicted the larger the error.\n",
    "You can read the theorems [here.](https://colab.research.google.com/github/john-s-butler-dit/Numerical-Analysis-Python/blob/master/Chapter%2001%20-%20Euler%20Methods/102_Euler_method_with_Theorems_nonlinear_Growth_function.ipynb) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "758afb8b",
   "metadata": {},
   "source": [
    "---\n",
    "# Section 4: Generalised Euler Method\n",
    "\n",
    "The Euler method can be applied to all first order differential equations of the form\n",
    "\\begin{align*}\n",
    "\\frac{d}{dt}y(t)&=f(t,y(t)),\\\\\n",
    "y(t_{0})&=y_0,\\\\\n",
    "\\end{align*}\n",
    "on an interval $[a,b]$.\n",
    "\n",
    "The differential equation can be written using the Euler method as\n",
    "\\begin{align*}\n",
    "\\frac{\\color{red}{y_{i+1}}-\\color{green}{y_i}}{\\color{blue}{\\Delta t}}&=f(\\color{blue}{t_i},\\color{green}{y_i}),\\\\\n",
    "\\color{red}{y_{i+1}}&=\\color{green}{y_i}+\\color{blue}{\\Delta t}f(\\color{blue}{t_i},\\color{green}{y_i}),\\\\\n",
    "&\\text{ for } i=0, \\cdots n-1,\\\\\n",
    "y(\\color{blue}{t_{0}})&=\\color{green}{y_0},\\\\\n",
    "\\end{align*}\n",
    "where  $\\color{red}{y_{i+1}}$ is the unknown estimate at $t_{i+1}$, $\\color{green}{y_i}$ is the known at $t_i$, $\\color{blue}{\\Delta t}$ is the chosen time-step parameter, $\\color{blue}{t_i}$ is the time point and $f$ is the right handside of the differential equation. \n",
    "The time discrete time stesp are:\n",
    "\\begin{align*}\n",
    "\\color{blue}{t_{i}}&=\\color{blue}{t_0}+\\color{blue}{i}\\color{blue}{\\Delta t},\\\\\n",
    "n&=\\frac{b-a}{\\Delta t}\\\\\n",
    "&\\text{ for } i=0, \\cdots n.\\\\\n",
    "\\end{align*}\n",
    "Once again this can be simply put into words:\n",
    "\\begin{align*}\n",
    "\\color{red}{\\text{ \"Future\" }}&=\\color{green}{\\text{ \"Current Info\" }}+\\color{blue}{\\text{ time-step } }\\times\\text{ \"Dynamics of the system which is a function of } \\color{blue}{ \\text{ time }} \\text{ and }\\color{green}{ \\text{ Current Info.\" }}\n",
    "\\end{align*}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b419bf50",
   "metadata": {},
   "source": [
    "---\n",
    "# Section 5: Euler Method for the Leaky Integrate and Fire"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "JOA7EzauxIV6",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:31.048294Z",
     "iopub.status.busy": "2021-06-02T02:46:31.047733Z",
     "iopub.status.idle": "2021-06-02T02:46:31.116245Z",
     "shell.execute_reply": "2021-06-02T02:46:31.116726Z"
    }
   },
   "outputs": [],
   "source": [
    "#@title Video 2: Leaky Integrate and Fire Model\n",
    "video = YouTubeVideo(id=\"JWI2msDBZ7o\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtu.be/\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "Zjro4hXwxU8O",
   "metadata": {},
   "source": [
    "The Leaky Integrare and Fire differential equation is:\n",
    "\n",
    "\\begin{align}\n",
    "\\frac{dV}{dt} = \\frac{-(V-E_L) + R_mI(t)}{\\tau_m}\\,\n",
    "\\end{align}\n",
    "\n",
    "where $\\tau_m$ is the time constant, $V$ is the membrane potential, $E_L$ is the resting potential, $R_m$ is leak resistance and $I(t)$ is the external input current. \n",
    "\n",
    "The solution can be estimated by applyting the Euler method to give the difference equation:\n",
    "\n",
    "\\begin{align}\n",
    "\\frac{\\color{red}{V_{i+1}}-\\color{green}{V_{i}}}{\\color{blue}{\\Delta t}}=\\big(\\frac{-(\\color{green}{V_i}-\\color{blue}{E_L}) + \\color{blue}{R_m}I_i}{\\color{blue}{\\tau_m}}\\big),\\\\\n",
    "\\end{align}\n",
    "\n",
    "Re-arranging gives:\n",
    "\n",
    "\\begin{align}\n",
    "\\color{red}{V_{i+1}}=\\color{green}{V_{i}}+\\color{blue}{\\Delta t}\\big(\\frac{-(\\color{green}{V_i}-\\color{blue}{E_L}) + \\color{blue}{R_m}I_i}{\\color{blue}{\\tau_m}}\\big),\\\\\n",
    "\\text{for } i=0\\cdots n-1,\n",
    "\\end{align}\n",
    "\n",
    "where $\\color{red}{V_{i+1}}$ is unknown, $\\color{green}{V_{i}} $ is known, $\\color{blue}{E_L}$, $\\color{blue}{R_m}$ and $\\color{blue}{\\tau_m}$ are known parameters, $\\color{blue}{\\Delta t}$ is a chosen time-step and  $I(t_i)$ is a function for an external input current."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1efb9d89",
   "metadata": {},
   "source": [
    "## Coding Exercise 5: LIF and Euler\n",
    "Code the difference equation for the LIF:\n",
    "\n",
    "\\begin{align}\n",
    "\\color{red}{V_{i+1}}=\\color{green}{V_{i}}+\\color{blue}{\\Delta t}\\big(\\frac{-(\\color{green}{V_i}-\\color{blue}{E_L}) + \\color{blue}{R_m}I_i}{\\color{blue}{\\tau_m}}\\big),\\\\\n",
    "\\text{for } i=0\\cdots n-1,\n",
    "\\end{align}\n",
    "\n",
    "with the given parameters set as:\n",
    "* `V_reset = -75,`\n",
    "* `E_L = -75,`\n",
    "* `tau_m = 10,`\n",
    "* `R_m = 10.`\n",
    "\n",
    "\n",
    "The plot below is a figure with with three panels; \n",
    "* the top panel is the sinusoidal input, $I$, \n",
    "* the middle panel is the estimate membrane potential $V_i$ to illustrative the spike $V_i$ is set to $0$ and then reset, \n",
    "* the bottom panel is the raster plot with each dot indicating a spike.\n",
    "\n",
    "As electrophysiologists normally listen to spikes when conducting experiments,  listen to the music of different firing rates by changing the input value $I$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e7d29bb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:31.125105Z",
     "iopub.status.busy": "2021-06-02T02:46:31.123601Z",
     "iopub.status.idle": "2021-06-02T02:46:31.125754Z",
     "shell.execute_reply": "2021-06-02T02:46:31.126216Z"
    }
   },
   "outputs": [],
   "source": [
    "def Euler_Integrate_and_Fire(I, time, dt):\n",
    "  \"\"\"\n",
    "  Args:\n",
    "    I: Input\n",
    "    time: time\n",
    "    dt: time-step\n",
    "  Returns:\n",
    "    Spike: Spike count\n",
    "    Spike_time: Spike times\n",
    "    V: membrane potential esitmated by the Euler method\n",
    "  \"\"\"\n",
    "\n",
    "  Spike = 0\n",
    "  tau_m = 10\n",
    "  R_m = 10\n",
    "  t_isi = 0\n",
    "  V_reset = E_L = -75\n",
    "  n = len(time)\n",
    "  V = V_reset * np.ones(n)\n",
    "  V_th = -50\n",
    "  Spike_time = []\n",
    "\n",
    "  for i in range(n-1):\n",
    "    #######################################################################\n",
    "    ## TODO for students: calculate the estimate solution of V at t[i+1]\n",
    "    ## Complete line of codes for dV and remove\n",
    "    ## Run the code in Section 5.1 or 5.2 to see the output!\n",
    "    raise NotImplementedError(\"Student exercise: calculate the estimate solution of V at t[i+1]\")\n",
    "    ########################################################################\n",
    "\n",
    "    dV = ...\n",
    "    V[i+1] = V[i] + dt*dV\n",
    "\n",
    "    # Discontinuity for Spike\n",
    "    if V[i] > V_th:\n",
    "      V[i] = 0\n",
    "      V[i+1] = V_reset\n",
    "      t_isi = time[i]\n",
    "      Spike = Spike + 1\n",
    "      Spike_time = np.append(Spike_time, time[i])\n",
    "\n",
    "  return Spike, Spike_time, V"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55785e26",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:31.134577Z",
     "iopub.status.busy": "2021-06-02T02:46:31.132917Z",
     "iopub.status.idle": "2021-06-02T02:46:31.135255Z",
     "shell.execute_reply": "2021-06-02T02:46:31.135723Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_c27085de.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d322dc9",
   "metadata": {},
   "source": [
    "## Section 5.1: Sinusoidal Input to LIF\n",
    "The plot below shows the estimated solution of the LIF using the Euler method for a sinusoidal input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd8f60c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:31.153136Z",
     "iopub.status.busy": "2021-06-02T02:46:31.143625Z",
     "iopub.status.idle": "2021-06-02T02:46:31.610467Z",
     "shell.execute_reply": "2021-06-02T02:46:31.610947Z"
    }
   },
   "outputs": [],
   "source": [
    "dt = 1\n",
    "t = np.arange(0, 1000, dt)\n",
    "I = np.sin(4 * 2 * np.pi * t/1000) + 2\n",
    "Spike, Spike_time, V = Euler_Integrate_and_Fire(I, t, dt)\n",
    "\n",
    "plot_IF(t, V,I,Spike_time)\n",
    "ipd.Audio(V, rate=1000/dt)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79e532a7",
   "metadata": {},
   "source": [
    "### Section 5.2: Random Input to the LIF\n",
    "The plot below shows a figure with with three panels; \n",
    "* the top panel is the noisy input, $I_i$, \n",
    "* the middle panel is the estimate membrane potential $V_i$ to illustrative the spike $V_i$ is set to $0$ and then reset, \n",
    "* the bottom panel is the raster plot with each dot indicating a spike.\n",
    "\n",
    "Listen to the music of different firing rates for a noisy input $I$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1cbad307",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:31.660031Z",
     "iopub.status.busy": "2021-06-02T02:46:31.654640Z",
     "iopub.status.idle": "2021-06-02T02:46:32.113596Z",
     "shell.execute_reply": "2021-06-02T02:46:32.113100Z"
    }
   },
   "outputs": [],
   "source": [
    "dt = 1\n",
    "t = np.arange(0, 1000, dt)\n",
    "I = np.random.randn(len(t)) + 2.5\n",
    "Spike, Spike_time, V = Euler_Integrate_and_Fire(I, t, dt)\n",
    "\n",
    "plot_IF(t, V, I, Spike_time)\n",
    "ipd.Audio(V, rate=1000/dt)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "L5o2liqz3bxi",
   "metadata": {},
   "source": [
    "---\n",
    "# Section 6: Systems of Differential Equations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "AEkCMPyt3iG_",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:32.120795Z",
     "iopub.status.busy": "2021-06-02T02:46:32.120224Z",
     "iopub.status.idle": "2021-06-02T02:46:32.189279Z",
     "shell.execute_reply": "2021-06-02T02:46:32.190120Z"
    }
   },
   "outputs": [],
   "source": [
    "#@title Video 3: Systems of Differential Equations\n",
    "from IPython.display import YouTubeVideo\n",
    "video = YouTubeVideo(id=\"0rTYV7g0edM\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtu.be/\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85df22b9",
   "metadata": {},
   "source": [
    "To get to grips with solving a system of differential equations using the Euler method, we will simplify the Wilson Cowan model, a set of equations that will be exploted in more detail on W?D?. The next few sections will apply the Euler method to a system of equations and will also give you a feel of a how to investigate a system of differential equations.\n",
    "\n",
    "We will start with a linear version of the Wilson Cowan model. Consider the equations, \n",
    "\n",
    "\\begin{align}\n",
    "\\tau_E \\frac{dr_E}{dt} &= w_{EE}r_E+w_{EI}r_I \\\\\n",
    "\\tau_I \\frac{dr_I}{dt} &= w_{IE}r_E+w_{II}r_I\n",
    "\\end{align}\n",
    "\n",
    "$r_E(t)$ represents the average activation (or firing rate) of the excitatory population at time $t$, and $r_I(t)$ the activation (or firing rate) of the inhibitory population. The parameters $\\tau_E$ and $\\tau_I$ control the timescales of the dynamics of each population. Connection strengths are given by: $w_{EE}$ (E $\\rightarrow$ E), $w_{EI}$ (I $\\rightarrow$ E), $w_{IE}$ (E $\\rightarrow$ I), and $w_{II}$ (I $\\rightarrow$ I). The terms $w_{EI}$ and $w_{IE}$ represent connections from inhibitory to excitatory population and vice versa, respectively. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "067b5f6e",
   "metadata": {},
   "source": [
    "## Coding Exercise 6: Euler on a Simple System \n",
    "We will further simplify the equations by setting $w_{EE}$ and $w_{II}$ to zero, we now have the equations \n",
    "\n",
    "\\begin{align}\n",
    "\\tau_E \\frac{dr_E}{dt} &= w_{EI}r_I, \\\\\n",
    "\\tau_I \\frac{dr_I}{dt} &= w_{IE}r_E, \\qquad (1)\n",
    "\\end{align}\n",
    "\n",
    "where $\\tau_E=100$ and $\\tau_I=120$, no internal connection $w_{EE}=w_{II}=0$, and $w_{EI}=-1$ and $w_{IE}=1$,\n",
    "with the initial conditions\n",
    "\n",
    "\\begin{align}\n",
    "r_E(0)=30, \\\\ \n",
    "r_I(0)=20.\n",
    "\\end{align}\n",
    "\n",
    "The solution can be approximated using the Euler method such that we have the difference equations:\n",
    "\n",
    "\\begin{align*}\n",
    "\\frac{\\color{red}{rE_{i+1}}-\\color{green}{rE_i}}{\\color{blue}{\\Delta t}}&=\\big(\\frac{\\color{blue}{w_{EI}}\\color{green}{rI_i}}{\\color{blue}{\\tau_E}}\\big),\\\\\n",
    "\\frac{\\color{red}{rI_{i+1}}-\\color{green}{rI_i}}{\\color{blue}{\\Delta t}}&=\\big(\\frac{\\color{blue}{w_{IE}}\\color{green}{rE_i}}{\\color{blue}{\\tau_I}}\\big),\\\\\n",
    "\\end{align*}\n",
    "\n",
    "Re-arranging:\n",
    "\n",
    "\\begin{align*}\n",
    "\\color{red}{rE_{i+1}}&=\\color{green}{rE_i}+\\color{blue}{\\Delta t}\\big(\\frac{\\color{blue}{w_{EI}}\\color{green}{rI_i}}{\\color{blue}{\\tau_E}}\\big),\\\\\n",
    "\\color{red}{rI_{i+1}}&=\\color{green}{rI_i}+\\color{blue}{\\Delta t}\\big(\\frac{\\color{blue}{w_{IE}}\\color{green}{rE_i}}{\\color{blue}{\\tau_I}}\\big),\\\\\n",
    "&\\text{ for  } i=0, \\cdots , n-1,\\\\\\\\\n",
    "rE_0&=30,\\\\\n",
    "rI_0&=20.\\\\\n",
    "\\end{align*}\n",
    "\n",
    "where $\\color{red}{rE_{i+1}}$ and  $\\color{red}{rI_{i+1}}$ are unknown, $\\color{green}{rE_{i}} $ and  $\\color{green}{rI_{i}} $ are known, $\\color{blue}{w_{EI}}=-1$, $\\color{blue}{w_{IE}}=1$ and $\\color{blue}{\\tau_E}=100$ and $\\color{blue}{\\tau_I}=120$  are known parameters and $\\color{blue}{\\Delta t}$ is a chosen time-step.\n",
    "\n",
    "__Code the difference equations to estimate $r_{E}$ and $r_{I}$.__\n",
    "\n",
    "Note that the equations have to estimated in the same `for` loop as they depend on each other."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1514105",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:32.198871Z",
     "iopub.status.busy": "2021-06-02T02:46:32.196980Z",
     "iopub.status.idle": "2021-06-02T02:46:32.207518Z",
     "shell.execute_reply": "2021-06-02T02:46:32.206859Z"
    }
   },
   "outputs": [],
   "source": [
    "def Euler_Simple_Linear_System(t, dt):\n",
    "  \"\"\"\n",
    "  Args:\n",
    "    time: time\n",
    "  dt  : time-step\n",
    "  Returns:\n",
    "    r_E : Excitation Firing Rate\n",
    "    r_I : Inhibition Firing Rate\n",
    "\n",
    "  \"\"\"\n",
    "\n",
    "  tau_E = 100\n",
    "  tau_I = 120\n",
    "  n = len(t)\n",
    "  r_I = 20*np.ones(n)\n",
    "  r_E = 30*np.ones(n)\n",
    "\n",
    "  #######################################################################\n",
    "  ## TODO for students: calculate the estimate solutions of r_E and r_I at t[i+1]\n",
    "  ## Complete line of codes for dr_E and dr_I and remove\n",
    "  raise NotImplementedError(\"Student exercise: calculate the estimate solutions of r_E and r_I at t[i+1]\")\n",
    "  ########################################################################\n",
    "\n",
    "  for i in range(n-1):\n",
    "    dr_E = ...\n",
    "    r_E[i+1] = r_E[i] + dt*dr_E\n",
    "\n",
    "    dr_I = ...\n",
    "    r_I[i+1] = r_I[i] + dt*dr_I\n",
    "\n",
    "  return r_E, r_I\n",
    "\n",
    "\n",
    "dt = 0.1 # time-step\n",
    "t = np.arange(0, 1000, dt)\n",
    "r_E, r_I = Euler_Simple_Linear_System(t, dt)\n",
    "plot_rErI(t, r_E, r_I)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb4e8ac5",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:32.224768Z",
     "iopub.status.busy": "2021-06-02T02:46:32.213421Z",
     "iopub.status.idle": "2021-06-02T02:46:32.580350Z",
     "shell.execute_reply": "2021-06-02T02:46:32.579843Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_cce398e8.py)\n",
    "\n",
    "*Example output:*\n",
    "\n",
    "<img alt='Solution hint' align='left' width=416 height=272 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W0D4_Calculus/static/W0D4_Tutorial3_Solution_cce398e8_0.png>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "Fk-EvkAOImKR",
   "metadata": {},
   "source": [
    "### Think! 6: Simple Euler Solution to the Wilson Cowan model\n",
    "\n",
    "1. Is the simulation biologically plausible?\n",
    "2. What is the effect of combined excitation and inhibition?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "i3L1OGeUgZEe",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:32.585801Z",
     "iopub.status.busy": "2021-06-02T02:46:32.584822Z",
     "iopub.status.idle": "2021-06-02T02:46:32.587627Z",
     "shell.execute_reply": "2021-06-02T02:46:32.588094Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_13ffd604.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecb0c3bf",
   "metadata": {},
   "source": [
    "## Section 6.1: Phase Plane Plot and Nullcline\n",
    "When there are two differential equations describing the interaction of two processes like excitation $r_{E}$ and inhibition $r_{I}$ that are both dependent on each other one way of plotting them is as a function of each other which is called a phase plane plot. The phase plane plot can give insight give insight into the state of the system but more about that later in Neuromatch Academy.\n",
    "\n",
    "An addition to the phase plane plot are the \"nullcline\". These lines plot when the rate of change $\\frac{d}{dt}$ of the variables is equation to $0$. We saw a variation of this for a single differential equation in the differential equation tutorial.\n",
    "\n",
    "As we have have two differential equations we set $\\frac{dr_E}{dt}=0$ and $\\frac{dr_I}{dt}=0$ which gives the equations,\n",
    "\n",
    "\\begin{align}\n",
    "0&= w_{EI}r_I, \\\\\n",
    "0&= w_{IE}r_E,\\\\\n",
    "\\end{align}\n",
    "\n",
    "these are a unique example as they are a vertical and horizontal line. Where the lines cross is the stable point which the $r_E(t)$ excitatory population and $r_I(t)$ the inhibitory population orbit around.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "036d3fb5",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:32.612592Z",
     "iopub.status.busy": "2021-06-02T02:46:32.611981Z",
     "iopub.status.idle": "2021-06-02T02:46:33.195449Z",
     "shell.execute_reply": "2021-06-02T02:46:33.194253Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown Excute the code to plot the solution to the system\n",
    "plot_rErI_Simple(t, r_E, r_I)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98f3c696",
   "metadata": {},
   "source": [
    "### Think! 6.1: Discuss the Plots\n",
    "\n",
    "1. Which representation is more intuitive (and useful), the time plot or the phase plane plot?\n",
    "2. Why do we only see one circle? \n",
    "3. What do the quadrants represent?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "Sfa1foAYhB13",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:33.200034Z",
     "iopub.status.busy": "2021-06-02T02:46:33.199443Z",
     "iopub.status.idle": "2021-06-02T02:46:33.201803Z",
     "shell.execute_reply": "2021-06-02T02:46:33.202272Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_92736bfb.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a278386",
   "metadata": {},
   "source": [
    "---\n",
    "# Section 7: Linear System of Differential Equations\n",
    "\n",
    "Building up the equations in the previous section we re-introduce internal connections $w_{EE}$, $w_{II}$. The two coupled differential equations, each representing the dynamics of the excitatory or inhibitory population are now:\n",
    "\n",
    "\\begin{align}\n",
    "\\tau_E \\frac{dr_E}{dt} &=w_{EE}r_E +w_{EI}r_I, \\\\\n",
    "\\tau_I \\frac{dr_I}{dt} &=w_{IE}r_E +w_{II}r_I ,\n",
    "\\end{align}\n",
    "\n",
    "where $\\tau_E=100$ and $\\tau_I=120$, $w_{EE}=1$ and $w_{II}=-1$, and $w_{EI}=-5$ and $w_{IE}=0.6$,\n",
    "with the initial conditions\n",
    "\n",
    "\\begin{align}\n",
    "r_E(0)=30, \\\\ \n",
    "r_I(0)=20.\n",
    "\\end{align}\n",
    "\n",
    "The solution can be approximated using the Euler method such that the equations become:\n",
    "\n",
    "\\begin{align*}\n",
    "\\frac{\\color{red}{rE_{i+1}}-\\color{green}{rE_i}}{\\color{blue}{\\Delta t}}&=\\big(\\frac{\\color{blue}{w_{EE}}\\color{green}{rE_i}+\\color{blue}{w_{EI}}\\color{green}{rI_i}}{\\color{blue}{\\tau_E}}\\big),\\\\\n",
    "\\frac{\\color{red}{rI_{i+1}}-\\color{green}{rI_i}}{\\color{blue}{\\Delta t}}&=\\big(\\frac{\\color{blue}{w_{II}}\\color{green}{rI_i}+\\color{blue}{w_{IE}}\\color{green}{rE_i}}{\\color{blue}{\\tau_I}}\\big),\\\\\n",
    "\\end{align*}\n",
    "\n",
    "Re-arranging:\n",
    "\n",
    "\\begin{align*}\n",
    "\\color{red}{rE_{i+1}}&=\\color{green}{rE_i}+\\color{blue}{\\Delta t}\\big(\\frac{\\color{blue}{w_{EE}}\\color{green}{rE_i}+\\color{blue}{w_{EI}}\\color{green}{rI_i}}{\\color{blue}{\\tau_E}}\\big),\\\\\n",
    "\\color{red}{rI_{i+1}}&=\\color{green}{rI_i}+\\color{blue}{\\Delta t}\\big(\\frac{\\color{blue}{w_{II}}\\color{green}{rI_i}+\\color{blue}{w_{IE}}\\color{green}{rE_i}}{\\color{blue}{\\tau_I}}\\big),\\\\\n",
    "&\\text{ for } i=0, \\cdots n-1,\\\\\\\\\n",
    "rE_0&=30,\\\\\n",
    "rI_0&=20.\\\\\n",
    "\\end{align*}\n",
    "\n",
    "where $\\color{red}{rE_{i+1}}$ and  $\\color{red}{rI_{i+1}}$ are unknown, $\\color{green}{rE_{i}} $ and  $\\color{green}{rI_{i}} $ are known, $\\color{blue}{w_{EI}}=-1$, $\\color{blue}{w_{IE}}=1$ and $\\color{blue}{\\tau_E}=100$ and $\\color{blue}{\\tau_I}=120$  are known parameters and $\\color{blue}{\\Delta t}=0.1$ is a chosen time-step."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b09028f",
   "metadata": {},
   "source": [
    "## Coding Exercise 7: Implement Euler for a System of Equations\n",
    "Code the Euler method for the linear system,\n",
    "\\begin{align}\n",
    "\\tau_E \\frac{dr_E}{dt} &=w_{EE}r_E +w_{EI}r_I, \\\\\n",
    "\\tau_I \\frac{dr_I}{dt} &=w_{IE}r_E +w_{II}r_I,\n",
    "\\end{align}\n",
    "\n",
    "where $\\tau_E=100$ and $\\tau_I=120$, $w_{EE}=1$ and $w_{II}=-1$, and $w_{EI}=-5$ and $w_{IE}=0.6$,\n",
    "with the initial conditions,\n",
    "\\begin{align}\n",
    "r_E(0)=30, \\\\ \n",
    "r_I(0)=20.\n",
    "\\end{align}\n",
    "While this might seem very repititive to an exercise above, it just shows how straightforward it is to convert a system of differential equations into simple pluses and minuses and a bit of multiplication."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "535cb86a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:33.210020Z",
     "iopub.status.busy": "2021-06-02T02:46:33.209432Z",
     "iopub.status.idle": "2021-06-02T02:46:33.219314Z",
     "shell.execute_reply": "2021-06-02T02:46:33.218412Z"
    }
   },
   "outputs": [],
   "source": [
    "def Euler_Linear_System_Matrix(t, dt, w_EE=1):\n",
    "  \"\"\"\n",
    "  Args:\n",
    "    time: time\n",
    "    dt: time-step\n",
    "    w_EE: Excitation to excitation weight\n",
    "  Returns:\n",
    "    r_E: Excitation Firing Rate\n",
    "    r_I: Inhibition Firing Rate\n",
    "    N_Er: Nullclines for drE/dt=0\n",
    "    N_Ir: Nullclines for drI/dt=0\n",
    "  \"\"\"\n",
    "\n",
    "  tau_E = 100\n",
    "  tau_I = 120\n",
    "  n = len(t)\n",
    "  r_I = 20*np.ones(n)\n",
    "  r_E = 30*np.ones(n)\n",
    "  w_EI = -5\n",
    "  w_IE = 0.6\n",
    "  w_II = -1\n",
    "\n",
    "  for i in range(n-1):\n",
    "\n",
    "    ########################################################################\n",
    "    # TODO for students: compute drE and drI and remove\n",
    "    raise NotImplementedError(\"Student exercise: compute drE and drI\")\n",
    "    ########################################################################\n",
    "\n",
    "    # Calculate the derivatives of the E and I populations\n",
    "    drE = ...\n",
    "    r_E[i+1] = r_E[i] + dt*drE\n",
    "\n",
    "    drI = ...\n",
    "    r_I[i+1] = r_I[i] + dt*drI\n",
    "\n",
    "  N_Er = -w_EE / w_EI*r_E\n",
    "  N_Ir = -w_IE / w_II*r_E\n",
    "\n",
    "  return r_E, r_I, N_Er, N_Ir\n",
    "\n",
    "dt = 0.1 # time-step\n",
    "t = np.arange(0, 1000, dt)\n",
    "r_E, r_I, _, _ = Euler_Linear_System_Matrix(t, dt)\n",
    "plot_rErI(t, r_E, r_I)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e00d88fb",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:33.251558Z",
     "iopub.status.busy": "2021-06-02T02:46:33.242254Z",
     "iopub.status.idle": "2021-06-02T02:46:33.529456Z",
     "shell.execute_reply": "2021-06-02T02:46:33.528930Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_e9b2af6f.py)\n",
    "\n",
    "*Example output:*\n",
    "\n",
    "<img alt='Solution hint' align='left' width=416 height=272 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W0D4_Calculus/static/W0D4_Tutorial3_Solution_e9b2af6f_0.png>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "byUkHQNsJDF-",
   "metadata": {},
   "source": [
    "### Think! 7: Oscillations\n",
    "\n",
    "\n",
    "1. What will happen to the oscillations if the time period is extended? \n",
    "2. How would you control or predict the oscillations? "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ACUE5rriyyR",
   "metadata": {
    "colab_type": "text",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:33.535402Z",
     "iopub.status.busy": "2021-06-02T02:46:33.534733Z",
     "iopub.status.idle": "2021-06-02T02:46:33.537632Z",
     "shell.execute_reply": "2021-06-02T02:46:33.538108Z"
    }
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D4_Calculus/solutions/W0D4_Tutorial3_Solution_5929a354.py)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "261b8f71",
   "metadata": {},
   "source": [
    "## Section 7.1: Phase Plane and Nullclines\n",
    "\n",
    "Like before, we have two differential equations so we cane plot the results on a phase plane. We can also calculate the Nullclines when we set $\\frac{dr_E}{dt}=0$ and $\\frac{dr_I}{dt}=0$ which gives,\n",
    "\\begin{align}\n",
    "0&= w_{EE}r_E+w_{EI}r_I, \\\\\n",
    "0&= w_{IE}r_E+w_{II}r_I,\n",
    "\\end{align}\n",
    "re-arranging as two lines\n",
    "\\begin{align}\n",
    "r_I&= -\\frac{w_{EE}}{w_{EI}}r_E, \\\\\n",
    "r_I&= -\\frac{w_{IE}}{w_{II}}r_E, \n",
    "\\end{align}\n",
    "which crosses at the stable point. \n",
    "\n",
    "The panel on the left shows excitation firing rate $r_E$ and inhibition firing rate  $r_I$ as a function of time. On the rightside the phase plane plot shows inhibition firing rate $r_I$ as a function of excitiation firing rate $r_E$ with the Nullclines for $\\frac{dr_E}{dt}=0$ and $\\frac{dr_I}{dt}=0.$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ca5f555",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:33.557982Z",
     "iopub.status.busy": "2021-06-02T02:46:33.542120Z",
     "iopub.status.idle": "2021-06-02T02:46:34.228824Z",
     "shell.execute_reply": "2021-06-02T02:46:34.229283Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown *Run this cell to visualize the phase plane*\n",
    "dt = 0.1 # time-step\n",
    "t = np.arange(0, 1000, dt)\n",
    "r_E, r_I, N_Er, N_Ir = Euler_Linear_System_Matrix(t, dt)\n",
    "plot_rErI_Matrix(t, r_E, r_I, N_Er, N_Ir)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d220e96",
   "metadata": {},
   "source": [
    "### Interactive Demo 7.1: A small change changes everything\n",
    "To illustrate that even changing one parameter in system of differential equations has a large impact on the solutions of the excitation firing rate $r_E$ and inhibition firing rate $r_I$.\n",
    "Take note of:\n",
    "1. How the solution changes for positive and negative of $w_{EE}$ pay close attention to the axis.\n",
    "\n",
    "2. How would you maintain a stable oscillation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42724aca",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:34.254163Z",
     "iopub.status.busy": "2021-06-02T02:46:34.249294Z",
     "iopub.status.idle": "2021-06-02T02:46:34.879918Z",
     "shell.execute_reply": "2021-06-02T02:46:34.879409Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown Make sure you execute this cell to enable the widget!\n",
    "my_layout.width = '450px'\n",
    "@widgets.interact(\n",
    "    w_EE=widgets.FloatSlider(1, min=-1., max=2., step=.1,\n",
    "                                layout=my_layout)\n",
    ")\n",
    "\n",
    "def Pop_widget(w_EE):\n",
    "  dt = 0.1 # time-step\n",
    "  t = np.arange(0,1000,dt)\n",
    "  r_E, r_I, N_Er, N_Ir = Euler_Linear_System_Matrix(t, dt, w_EE)\n",
    "  plot_rErI_Matrix(t, r_E, r_I, N_Er, N_Ir)\n",
    "  plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1268fd80",
   "metadata": {},
   "source": [
    "---\n",
    "# Take Home\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "kyb5XuAb9H6G",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:34.887468Z",
     "iopub.status.busy": "2021-06-02T02:46:34.886823Z",
     "iopub.status.idle": "2021-06-02T02:46:34.954422Z",
     "shell.execute_reply": "2021-06-02T02:46:34.955007Z"
    }
   },
   "outputs": [],
   "source": [
    "#@title Video 4: Numerical Methods - Take Home and Bonus Materials\n",
    "video = YouTubeVideo(id=\"NDXcNZXeLsw\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtu.be/\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "-JZJWqTnitQx",
   "metadata": {},
   "source": [
    "Using pretty much the formula for the slope of a line, the solution of differential equation can be estimated with reasonable accuracy. \n",
    "This will be much more relevant when dealing with more complicated (non-linear) differential equations where there is no known exact solution."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a038940e",
   "metadata": {},
   "source": [
    "---\n",
    "# Links to Neuromatch Days\n",
    "\n",
    "The Euler method is used to estimate differential equations in a number of different Neuromatch days:\n",
    "* The LIF model is discussed in more details in Model Types (Week 1 Day 1) and Real Neurons (Week 2 Day 3).\n",
    "* Drift Diffusion model which is a differential equation for decision making is discussed in Linear Systems (Week 2 Day 2).\n",
    "* Phase-plane plots are discussed in Linear Systems (Week 2 Day 2) and Dynamic Networks (Week 2 Day 4).\n",
    "* The Wilson-Cowan model is discussed in Dynamic Networks (Week 2 Day 4).\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a307a8fa",
   "metadata": {},
   "source": [
    "---\n",
    "# References \n",
    "1. Lotka, A. L, (1920)   Analytical note on certain rhythmic  relations inorganic  systems.Proceedings of the National Academy of Sciences,6(7):410–415,1920.\n",
    "\n",
    "2. Brunel N, van Rossum MC. Lapicque's 1907 paper: from frogs to integrate-and-fire. Biol Cybern. 2007 Dec;97(5-6):337-9. doi: 10.1007/s00422-007-0190-0. Epub 2007 Oct 30. PMID: 17968583.\n",
    "\n",
    "\n",
    "\n",
    "# Bibliography\n",
    "1. Dayan, P., & Abbott, L. F. (2001). Theoretical neuroscience: computational and mathematical modeling of neural systems. Computational Neuroscience Series.\n",
    "2. Strogatz, S. Nonlinear dynamics and chaos: with applications to physics, biology, chemistry, and engineering (studies in nonlinearity), Westview Press; 2 edition (29 July 2014)\n",
    "\n",
    "## Supplemental Popular Reading List\n",
    "1. Lindsay, G. (2021). Models of the Mind: How Physics, Engineering and Mathematics Have Shaped Our Understanding of the Brain. Bloomsbury Publishing.\n",
    "2. Strogatz, S. (2004). Sync: The emerging science of spontaneous order. Penguin UK.\n",
    "\n",
    "## Popular Podcast\n",
    "1. Strogatz, S. (Host). (2020-), Joy of X  https://www.quantamagazine.org/tag/the-joy-of-x/ Quanta Magazine"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c9b3f6e",
   "metadata": {},
   "source": [
    "---\n",
    "# Bonus 1: The 4th Order Runge Kutta\n",
    "Another popular numerical method to estimate the solution of a differential equations of the general form: \n",
    "$$ \\frac{d}{dt}y=f(t,y)$$\n",
    "is the 4th Order Runge Kutta: \n",
    "$$k_1=f(t,y),$$\n",
    "$$k_2=f(t+\\frac{\\Delta t}{2},y+\\frac{\\Delta t}{2}k_1),$$\n",
    "$$k_3=f(t+\\frac{\\Delta t}{2},y+\\frac{\\Delta t}{2}k_2),$$\n",
    "$$k_4=f(t+dt,y+\\Delta tk_3),$$\n",
    "$$y_{i+1}=y_{i}+\\frac{\\Delta t}{6}(k_1+2k_2+2k_3+k_4),$$\n",
    "which is more accurate than the Euler method.\n",
    "\n",
    "Given the population differential equation\n",
    "\\begin{align*}\n",
    "\\\\\n",
    "\\frac{d}{dt}\\,p(t) &= 0.3 p(t)\\\\\n",
    "p(t_0=1)&=e^{0.3}\\quad \\text{Initial Condition}\n",
    "\\end{align*}\n",
    "the 4th Runge Kutta difference equation is\n",
    "\\begin{align*}\n",
    "k_1&=0.3\\color{green}{p_i},\\\\\n",
    "k_2&=0.3(\\color{green}{p_i}+\\frac{\\Delta t}{2}k_1),\\\\\n",
    "k_3&=0.3(\\color{green}{p_i}+\\frac{\\Delta t}{2}k_2),\\\\\n",
    "k_4&=0.3(\\color{green}{p_i}+k_3),\\\\\n",
    "\\color{red}{p_{i+1}}&=\\color{green}{p_i}+\\frac{\\color{blue}{\\Delta t}}{6}( \\color{green}{k_1+2k_2+2k_3+k_4})\\\\\n",
    "&\\text{for } i=0,1,\\cdots 4\n",
    "\\end{align*}\n",
    "to estimate the population for $\\Delta t=0.5$.\n",
    "\n",
    "The code is implemented below. Note how much more accurate the 4th Order Runge Kutta (yellow) is compared to the Euler Method (blue).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b936428",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:34.980305Z",
     "iopub.status.busy": "2021-06-02T02:46:34.962793Z",
     "iopub.status.idle": "2021-06-02T02:46:35.301800Z",
     "shell.execute_reply": "2021-06-02T02:46:35.301302Z"
    }
   },
   "outputs": [],
   "source": [
    "dt=0.5\n",
    "\n",
    "t=np.arange(1, 5+dt/2, dt)\n",
    "\n",
    "n = len(t)\n",
    "p = np.ones(n)\n",
    "pRK4 = np.ones(n)\n",
    "p[0] = np.exp(0.3*t[0])\n",
    "pRK4[0] = np.exp(0.3*t[0])# Initial Condition\n",
    "\n",
    "with plt.xkcd():\n",
    "\n",
    "  fig = plt.figure(figsize=(6, 4))\n",
    "  plt.plot(t, np.exp(0.3*t), 'k', label='Exact Solution')\n",
    "\n",
    "  for i in range(n-1):\n",
    "    dp = dt*0.3*p[i]\n",
    "    p[i+1] = p[i] + dp # Euler\n",
    "    k1 = 0.3*(pRK4[i])\n",
    "    k2 = 0.3*(pRK4[i] + dt/2*k1)\n",
    "    k3 = 0.3*(pRK4[i] + dt/2*k2)\n",
    "    k4 = 0.3*(pRK4[i] + dt*k3)\n",
    "    pRK4[i+1] = pRK4[i] + dt/6 *(k1 + 2*k2 + 2*k3 + k4)\n",
    "\n",
    "  plt.plot(t, p,':o', label='Euler Estimate')\n",
    "  plt.plot(t, pRK4,':o', color='y', label='4th Order Runge Kutta Estimate')\n",
    "  plt.vlines(t,p,np.exp(0.3*t),colors='r', linestyles='dashed',label=r'Error $e_i$')\n",
    "\n",
    "  plt.plot(t[0], p[0], 'go', label='Intial Condition')\n",
    "  plt.ylabel('Population (millions)')\n",
    "  plt.legend()\n",
    "  plt.xlabel('Time (years)')\n",
    "  plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "W7ziQulJL6Kl",
   "metadata": {},
   "source": [
    "### Bonus Reference 1: A full course on numerical methods in Python\n",
    "\n",
    "For a full course on Numerical Methods you can look here https://github.com/john-s-butler-dit/Numerical-Analysis-Python"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "jXpJytN7dgYn",
   "metadata": {},
   "source": [
    "# Bonus 2: Neural oscillations are a start toward understanding brain activity rather than the end\n",
    "In an essay from May 2021 in PLOS Biology by Keith Dowling (a past Neuromatch TA) and M. Florencia Assaneo discussed a mathematical way of thinking about what should be defined as an oscillation.\n",
    "This is an important question as a good deal of research has investigated oscillations of the brain, and as we saw earlier, a good deal of the equations we use to model neuronal activity result in an oscillation.\n",
    "\n",
    "They motivated their approach using the Stuart–Landau equations which is a system of differential equations of the form\n",
    "\n",
    "\\begin{align}\n",
    " \\frac{dx}{dt} &=\\lambda x-\\omega y -\\gamma (x^2+y^2)x+s\\\\\n",
    " \\frac{dy}{dt} &=\\lambda y+\\omega x -\\gamma (x^2+y^2)y \n",
    "\\end{align}\n",
    "\n",
    "where $s$ is input to the system, and $\\lambda$, $\\omega$ and $\\gamma$ are parameters.\n",
    "The Stuart–Landau equations are a well described system of differential equations that generates oscillations. For their purpose, they used the equations to illustrate what people should expect when conducting experiments looking for oscilations. \n",
    "In their paper, using the Stuart–Landau equations, they outline \n",
    "* \"What is an oscillator?\"\n",
    "* \"What an oscillator is not\"\n",
    "* \"Not all that oscillates is oscillator\"\n",
    "* \"Not all oscillators are alike.\"\n",
    "\n",
    "The Euler form of the Stuart–Landau system of equations is:\n",
    "\\begin{align*}\n",
    "\\color{red}{x_{i+1}}&=\\color{green}{x_i}+\\color{blue}{\\Delta t}\\big(\\lambda \\color{green}{x_i}-\\omega \\color{green}{y_i} -\\gamma (\\color{green}{x_i}^2+\\color{green}{y_i}^2)\\color{green}{x_i}+s\\big),\\\\\n",
    "\\color{red}{y_{i+1}}&=\\color{green}{y_i}+\\color{blue}{\\Delta t}\\big(\\lambda \\color{green}{y_i}+\\omega \\color{green}{x_i} -\\gamma (\\color{green}{x_i}^2+\\color{green}{y_i}^2)\\color{green}{y_i} \\big),\\\\\n",
    "&\\text{ for } i=0, \\cdots n-1,\\\\\n",
    "x_0&=1,\\\\\n",
    "y_0&=1,\\\\\n",
    "\\end{align*}\n",
    "with $ \\Delta t=0.1/1000$ ms.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b9e30cc",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:35.314186Z",
     "iopub.status.busy": "2021-06-02T02:46:35.312898Z",
     "iopub.status.idle": "2021-06-02T02:46:35.314836Z",
     "shell.execute_reply": "2021-06-02T02:46:35.315336Z"
    }
   },
   "outputs": [],
   "source": [
    "# @title Helper functions\n",
    "def plot_Stuart_Landa(t, x, y, s):\n",
    "  \"\"\"\n",
    "    Args:\n",
    "      t  : time\n",
    "      x  : x\n",
    "      y  : y\n",
    "      s : input\n",
    "    Returns:\n",
    "      figure with two panels\n",
    "      top panel: Input as a function of time\n",
    "      bottom panel: x\n",
    "  \"\"\"\n",
    "\n",
    "  with plt.xkcd():\n",
    "    fig = plt.figure(figsize=(14, 4))\n",
    "    gs = gridspec.GridSpec(2, 2,  height_ratios=[1, 4], width_ratios=[4, 1])\n",
    "\n",
    "    # PLOT OF INPUT\n",
    "    plt.subplot(gs[0])\n",
    "    plt.ylabel(r'$s$')\n",
    "    plt.plot(t, s, 'g')\n",
    "    #plt.ylim((2,4))\n",
    "\n",
    "    # PLOT OF ACTIVITY\n",
    "    plt.subplot(gs[2])\n",
    "    plt.plot(t ,x)\n",
    "    plt.ylabel(r'x')\n",
    "    plt.xlabel(r't')\n",
    "    plt.subplot(gs[3])\n",
    "    plt.plot(x,y)\n",
    "    plt.plot(x[0], y[0],'go')\n",
    "    plt.xlabel(r'x')\n",
    "    plt.ylabel(r'y')\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def Euler_Stuart_Landau(s,time,dt,lamba=0.1,gamma=1,k=25):\n",
    "  \"\"\"\n",
    "  Args:\n",
    "    I: Input\n",
    "    time: time\n",
    "    dt: time-step\n",
    "  \"\"\"\n",
    "\n",
    "  n = len(time)\n",
    "  omega = 4 * 2*np.pi\n",
    "  x = np.zeros(n)\n",
    "  y = np.zeros(n)\n",
    "  x[0] = 1\n",
    "  y[0] = 1\n",
    "\n",
    "  for i in range(n-1):\n",
    "    dx = lamba*x[i] - omega*y[i] - gamma*(x[i]*x[i] + y[i]*y[i])*x[i] + k*s[i]\n",
    "    x[i+1] = x[i] + dt*dx\n",
    "    dy = lamba*y[i] + omega*x[i] - gamma*(x[i]*x[i] + y[i]*y[i])*y[i]\n",
    "    y[i+1] = y[i] + dt*dy\n",
    "\n",
    "  return x, y"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "H5inj2EKJyqN",
   "metadata": {},
   "source": [
    "### Bonus 2.1: What is an Oscillator?\n",
    "Doelling & Assaneo (2021), using the Stuart–Landau system, show different possible states of an oscilator by manipulating the $\\lambda$ term in the equation. \n",
    "From the paper: \"this qualitative change in behavior takes place at λ = 0: For λ < 0, the system decays to a stable equilibrium, while for λ > 0, it keeps oscillating.\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5MyIOK9w_qjd",
   "metadata": {},
   "source": [
    "#### Interactive Demo Bonus 2.1 \n",
    "The plot below shows the estimated solution of the Stuart–Landau system with a base frequency $\\omega$ set to $4\\times 2\\pi$, $\\gamma=1$ and $k=25$ over 3 seconds. The input to the system $s(t)$ is plotted in the top panel, $x$ as a function of time in the the bottom panel and on the right the phase plane plot of $x$ and $y$. You can manipulate $\\lambda$ to see how the oscilations change."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "LAnBGRU5crfG",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:35.338664Z",
     "iopub.status.busy": "2021-06-02T02:46:35.337202Z",
     "iopub.status.idle": "2021-06-02T02:46:36.036158Z",
     "shell.execute_reply": "2021-06-02T02:46:36.035644Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown Make sure you execute this cell to enable the widget!\n",
    "dt=0.1/1000\n",
    "t=np.arange(0, 3, dt)\n",
    "\n",
    "my_layout.width = '450px'\n",
    "@widgets.interact(\n",
    "    lamda=widgets.FloatSlider(1, min=-1., max=5., step=0.5,\n",
    "                                layout=my_layout)\n",
    ")\n",
    "\n",
    "def Pop_widget(lamda):\n",
    "    s=np.zeros(len(t))\n",
    "    x,y=Euler_Stuart_Landau(s,t,dt,lamda)\n",
    "    plot_Stuart_Landa(t, x, y, s)\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "q2OMPLOoKGtr",
   "metadata": {},
   "source": [
    "### Bonus 2.2 : Not all oscillators are alike"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "NLOVdwN5_ypj",
   "metadata": {},
   "source": [
    "#### Interactive Demo Bonus 2: Stuart-Landau System \n",
    "The plot below shows estimated solution of the Stuart–Landau system with a base frequency $\\omega$ set to $4\\times 2\\pi$, $\\lambda=1$, $\\gamma=1$ and $k=50$ over 3 seconds the input to the system $s(t)=\\sin(freq 2\\pi t) $ in the top panel, $x$ as a function of time in the the bottom panel and on the right the phase plane plot of $x$ and $y$. \n",
    "\n",
    "You can manipulate the frequency $freq$ of the input to see how the oscilations change and for frequencies $freq$ further and further from the base frequency of 4Hz the oscilations breaks down."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "XPuVG5f4clxt",
   "metadata": {
    "cellView": "form",
    "execution": {
     "iopub.execute_input": "2021-06-02T02:46:36.060875Z",
     "iopub.status.busy": "2021-06-02T02:46:36.060194Z",
     "iopub.status.idle": "2021-06-02T02:46:36.679833Z",
     "shell.execute_reply": "2021-06-02T02:46:36.678746Z"
    }
   },
   "outputs": [],
   "source": [
    "# @markdown Make sure you execute this cell to enable the widget!\n",
    "dt=0.1/1000\n",
    "t=np.arange(0, 3, dt)\n",
    "\n",
    "my_layout.width = '450px'\n",
    "@widgets.interact(\n",
    "    freq=widgets.FloatSlider(4, min=0.5, max=10., step=0.5,\n",
    "                                layout=my_layout)\n",
    ")\n",
    "\n",
    "def Pop_widget(freq):\n",
    "    s = np.sin(freq * 2*np.pi * t)\n",
    "\n",
    "    x, y = Euler_Stuart_Landau(s, t, dt, lamba=1, gamma=.1, k=50)\n",
    "    plot_Stuart_Landa(t, x, y, s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cWYP3SNL1Mh",
   "metadata": {},
   "source": [
    "### Bonus Reference 2\n",
    "[Doelling, K. B., & Assaneo, M. F. (2021). Neural oscillations are a start toward understanding brain activity rather than the end. PLoS biology, 19(5), e3001234.](https://journals.plos.org/plosbiology/article?id=10.1371/journal.pbio.3001234)\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "1cWYP3SNL1Mh"
   ],
   "include_colab_link": true,
   "name": "W0D4_Tutorial3",
   "provenance": [],
   "toc_visible": true
  },
  "kernel": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
